package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.RSAUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * 会员登录
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    //使用手机号和验证码登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) {

        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从Redis中获取缓存的验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);

        if (codeInRedis == null || !codeInRedis.equals(validateCode)) {
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        } else {

            //验证码输入正确
            //判断当前用户是否为会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                //当前用户不是会员，自动完成注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //登录成功
            //写入Cookie，跟踪用户
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60 * 60 * 24 * 30);//有效期30天
            response.addCookie(cookie);

            //保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(new String(RSAUtils.decodeBase64(telephone)), 60 * 30, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }
    }

    @RequestMapping("/findMember")
    public Result findMember(HttpServletRequest request) {
        try {
            //找到cookie电话
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if ("login_member_telephone".equals(cookie.getName())) {
                    String s = jedisPool.getResource().get(new String(RSAUtils.decodeBase64(cookie.getValue())));
                    Member member = JSON.parseObject(s, Member.class);
                    return new Result(true, MessageConstant.GET_MEMBER_MESSAGE_SUCCESS, member);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return new Result(false, MessageConstant.GET_MEMBER_MESSAGE_FAIL);
    }

    @RequestMapping("/updateById")
    public Result updateById(@RequestBody Member member) {
        try {
            memberService.update(member);
//            放入redis
            jedisPool.getResource().setex(new String(RSAUtils.decodeBase64(member.getPhoneNumber())), 30 * 60, JSON.toJSONString(member));
            return new Result(true, MessageConstant.UPDATE_SELF_IMFORMATION_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();

        }
        return new Result(false, MessageConstant.UPDATE_SELF_IMFORMATION_FAIL);
    }

    @RequestMapping("/myPhone")
    public Result myPhone(HttpServletRequest request) {

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("login_member_telephone".equals(cookie.getName())) {
                return new Result(true, MessageConstant.UPDATE_SELF_IMFORMATION_FAIL,cookie.getValue());
            }
        }
        return new Result(false, MessageConstant.UPDATE_SELF_IMFORMATION_FAIL);
    }
    @RequestMapping("/updatephoneNumber")
    public Result updatephoneNumber(@RequestParam("telephone")String number,@RequestParam("id")String id,HttpServletRequest request) {
        try {
            Member member=new Member();
            member.setPhoneNumber(number);
            Member byTelephone = memberService.findById(id);
            String phoneNumber = byTelephone.getPhoneNumber();
            member.setId(byTelephone.getId());
            memberService.update(member);
            jedisPool.getResource().del(new String(RSAUtils.decodeBase64(phoneNumber)));
            byTelephone.setPhoneNumber(number);
            //放入redis
            jedisPool.getResource().setex(new String(RSAUtils.decodeBase64(number)), 30 * 60, JSON.toJSONString(byTelephone));
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if ("login_member_telephone".equals(cookie.getName())) {
                    cookie.setValue(number);
                }
            }
            return new Result(true, MessageConstant.UPDATE_SELF_IMFORMATION_SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();

        }
        return new Result(false, MessageConstant.UPDATE_SELF_IMFORMATION_FAIL);
    }
    @RequestMapping("/findOldPassword")
    public Result findOldPassword(String oldPassword, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            //遍历cookies
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                //查询cookie名为login_member_telephone的值
                if ("login_member_telephone".equals(cookieName)) {
                    //获取到cookie中的值，即登陆者的手机号
                    String telephone = cookie.getValue();
                    //通过手机号码查询密码
                    Member member = memberService.findByTelephone(telephone);
                    if (member.getPassword()==null){
                        member.setPassword("123456");
                    }
                    if (member != null && oldPassword.equals(member.getPassword())) {
                        return new Result(true, MessageConstant.GET_ORDPASSWORD_SUCCESS);
                    }
                }
            }
        }
        return new Result(false, MessageConstant.GET_ORDPASSWORD_FAIL);
    }

    @RequestMapping("/updatePassword")
    public Result updatePassword(String newpassword, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            //遍历cookies
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                //查询cookie名为login_member_telephone的值
                if ("login_member_telephone".equals(cookieName)) {
                    //获取到cookie中的值，即登陆者的手机号
                    String telephone = cookie.getValue();
                    memberService.updatePassword(newpassword,telephone);
                    return new Result(true, MessageConstant.GET_UPDATE_PASSWORD_SUCCESS);
                }
            }
        }
        return new Result(false, MessageConstant.GET_UPDATE_PASSWORD_FAIL);
    }

}